<template>
  <div>
    <complex-table
      v-loading="uiOpts.loading"
      :data="uiPods"
      @search="reloadPodList"
    >
      <el-table-column :label="$t('commons.table.status')" min-width="45">
        <template #default="{ row }">
          <el-tag
            v-if="
              row.status.phase === 'Running' || row.status.phase === 'Succeeded'
            "
            type="success"
          >
            {{ row.status.phase }}
          </el-tag>
          <el-tag
            v-if="
              row.status.phase !== 'Running' && row.status.phase !== 'Succeeded'
            "
            type="warning"
          >
            {{ row.status.phase }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('commons.table.name')"
        prop="name"
        min-width="80"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span class="span-link" @click="openDetail(row)">{{
            row.metadata.name
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('business.namespace.namespace')"
        min-width="40"
        prop="metadata.namespace"
        show-overflow-tooltip
      />
      <el-table-column
        :label="$t('business.cluster.nodes')"
        min-width="40"
        prop="spec.nodeName"
        show-overflow-tooltip
      />
      <el-table-column
        :label="$t('business.pod.image')"
        min-width="120"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <div
            v-for="(item, index) in row.spec.containers"
            v-bind:key="index"
            class="myTag"
          >
            <el-tag type="info" size="small">
              {{ item.image }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="'Cpu'" min-width="45">
        <template #default="{ row }">
          {{ getPodUsage(row.metadata.name, "cpu") }}
        </template>
      </el-table-column>
      <el-table-column :label="'Memory'" min-width="45">
        <template #default="{ row }">
          {{ getPodUsage(row.metadata.name, "memory") }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('commons.table.created_time')"
        min-width="40"
        prop="metadata.creationTimestamp"
        show-overflow-tooltip
        fix
      >
        <template #default="{ row }">
          {{ row.metadata.creationTimestamp }}
        </template>
      </el-table-column>
      <ko-table-operations
        :buttons="uiOpts.operateButtons"
        :label="$t('commons.table.action')"
      />
    </complex-table>
  </div>
</template>

<script setup lang="ts">
import ComplexTable from "@/views/domain/kubeHud/views/components/complex-table/index.vue";
import KoTableOperations from "@/views/domain/kubeHud/views/components/ko-table-operations/index.vue";
import { Pod, useK8SApi } from "../../../api/k8s";
import { usePodOperation } from "../../../api/provider/podOperation";
import { onMounted, reactive, ref, watch } from "vue";
import {
  hasNsPodsexecCreatePermission,
  hasNsPodsListPermission,
  hasNsPodslogGetPermission
} from "../../../utils/permission";
import { useI18n } from "vue-i18n";
import { objectToString } from "../../../utils";
import { SafePromiseAll } from "@/utils/promise";
// import { listPodsWithNsSelector } from "@/api/pods";
// import { checkPermissions } from "@/utils/permission";
// import { listPodMetrics } from "@/api/apis";

const { podRepo, metric } = useK8SApi();
const { openTerminal, openTerminalLogs, router } = usePodOperation();
const { t } = useI18n();

type Prop = {
  cluster: string;
  namespace: string;
  selector?: { [key: string]: any };
  fieldSelector?: { [key: string]: any };
};

const props = withDefaults(defineProps<Prop>(), {
  cluster: "",
  namespace: ""
});

const uiOpts = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  loading: false,
  operateButtons: [
    {
      label: t("commons.button.terminal"),
      icon: "iconfont iconline-terminalzhongduan",
      click: (row: Pod) => {
        openTerminal({
          cluster: props.cluster,
          namespace: props.namespace,
          pod: row
        });
      },
      disabled: async () => {
        return await hasNsPodsexecCreatePermission();
      }
    },
    {
      label: t("commons.button.logs"),
      icon: "el-icon-tickets",
      click: (row: Pod) => {
        openTerminalLogs({
          cluster: props.cluster,
          namespace: props.namespace,
          pod: row
        });
      },
      disabled: async () => {
        return await hasNsPodslogGetPermission();
      }
    }
  ]
});

const uiPods = ref<Pod[]>([]);
const podUsage = ref<Record<string, any>>({});

const openDetail = (row: Pod) => {
  router.push({
    name: "PodDetail",
    params: { namespace: row.metadata.namespace, name: row.metadata.name },
    query: { yamlShow: "false" }
  });
};

const reloadPodList = async (resetPage?: boolean) => {
  uiOpts.loading = true;
  if (resetPage) {
    uiOpts.pageNum = 1;
  }

  if (!(await hasNsPodsListPermission())) {
    uiOpts.loading = false;
    return;
  }

  const [podRes, metricRes] = await SafePromiseAll([
    podRepo.getPodList({
      namespace: props.namespace,
      query: {
        labelSelector: objectToString(props.selector, ","),
        fieldSelector: objectToString(props.fieldSelector, ",")
      }
    }),
    podRepo.listPodMetrics({
      query: {
        labelSelector: objectToString(props.selector, ","),
        fieldSelector: objectToString(
          { "metadata.namespace": props.namespace },
          ","
        )
      }
    })
  ]).finally(() => {
    uiOpts.loading = false;
  });

  if (podRes?.items) {
    uiPods.value = podRes.items;
  }
  if (metricRes?.items) {
    metricRes.items.forEach(item => {
      podUsage.value[item.metadata.name] = item;
    });
    // podUsage.value = metricRes.items?.reduce((prev, curr) => {
    //   prev[curr.metadata.name] = curr;
    //   return prev;
    // });
  }
};

const getPodUsage = (name: string, type?: "cpu" | "memory") => {
  const pod = podUsage.value[name];
  if (!pod) {
    return "";
  }
  let usage = 0;
  pod?.containers?.forEach(item => {
    if (type === "cpu") {
      if (item.usage?.cpu?.indexOf("n") > -1) {
        usage += parseInt(item.usage.cpu);
      } else if (item.usage?.cpu?.indexOf("m") > -1) {
        usage += parseInt(item.usage.cpu) * 1000 * 1000;
      }
    } else if (type === "memory") {
      if (item.usage?.memory?.indexOf("Ki") > -1) {
        usage += parseInt(item.usage.memory);
      } else if (item.usage?.memory?.indexOf("Mi") > -1) {
        usage += parseInt(item.usage.memory) * 1000;
      }
    }
  });

  if (type === "cpu") {
    return `${(usage / 1000000).toFixed(2)} m`;
  } else {
    return `${(usage / 1000).toFixed(2)} Mi`;
  }
};

watch(
  () => props.selector,
  (ns, os) => {
    if (ns !== os) reloadPodList(true);
  }
);

watch(
  () => props.fieldSelector,
  (ns, os) => {
    if (ns !== os) reloadPodList(true);
  }
);

onMounted(() => {
  reloadPodList();
});
</script>

<style scoped>
.btnSize {
  width: 28px;
  height: 28px;
}
</style>
